import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import Moment from 'moment'
import { exportResponseData } from '@/utils/exportExcel'
// 创建 axios 实例
const instance = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 20000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  console.log('异常拦截处理器', error)
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
instance.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers[ACCESS_TOKEN] = token
  }
  // 移除无效调试日志，2023年9月24日01:27:24
  // console.log('config', config)
  return config
}, errorHandler)

// response interceptor
instance.interceptors.response.use((response) => {
  /**
     * 判断是否为excel文件【主要代码】
     */
  if (response.config.isExportExcel) {
    const data = response.data
    const contentType = response.headers['content-type']
    // let fileName
    // if (response.headers['content-disposition']) {
    //   fileName = decodeURI(
    //     response.headers['content-disposition'].match(/filename=(.*)/)[1]
    //   )
    // } else {
    //   fileName = (response.config.fileName || '') + '-' + new Moment().format('YYYYMMDD')
    // }
    const fileName = response.config.fileName ? response.config.fileName : `${new Moment().format('YYYYMMDD')}`
    exportResponseData(data, contentType, fileName)
    return true
  }
  if (response.data.code === 0) {
    return response.data
  }
  if (response.data.code === 401001) {
    // 登录凭证已过期，请重新登录
    store.dispatch('Logout').then(() => {
      setTimeout(() => {
        window.location.reload()
      }, 1500)
    })
  }
  // console.log('响应拦截', response)
  notification.error({
    message: response.data.code,
    description: response.data.msg
  })
  return Promise.reject(response.data)
}, errorHandler)

const request = (options) => {
  return new Promise((resolve, reject) => {
    instance(options).then(res => {
      resolve(res)
    }).catch(err=> {
      reject(err)
    })
  })
}
export default request
